﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;
using Core.Common;
using static Core.Common.Global;
using Tool.Web.HttpHelper;

namespace Core.Function
{
	public static class A2d
	{
		public static bool Ascii2dSearch(string imageurl, out Ascii2dSearchInfo searchresult, bool isbovw = false)
		{
			WebHeaderCollection webHeaderCollection = new WebHeaderCollection();
			searchresult = null;
			try
			{
				HttpNet.Get("https://ascii2d.net/search/url/" + imageurl, ref webHeaderCollection, null, null, null, 10000, Proxy, null, false, true);
				string text = webHeaderCollection["Location"];
				if (isbovw)
				{
					text = text.Replace("color", "bovw");
				}
				webHeaderCollection = new WebHeaderCollection();
				string @string = Encoding.UTF8.GetString(HttpNet.Get(text, null, null, null, 10000, Proxy, null, true, true));
				IHtmlCollection<IElement> htmlCollection = new HtmlParser().ParseDocument(@string).QuerySelectorAll("div.row.item-box");
				if (htmlCollection.Count() > 1)
				{
					IElement element = htmlCollection[1].QuerySelector("div.image-box img");
					searchresult = new Ascii2dSearchInfo();
					searchresult.ResultUrl = text;
					IHtmlCollection<IElement> htmlCollection2 = htmlCollection[1].QuerySelectorAll("h6 a");
					if (htmlCollection2.Count() > 1)
					{
						searchresult.Author = htmlCollection2[1].GetAttribute("href");
						searchresult.Url = htmlCollection2[0].GetAttribute("href");
					}
					if (element != null)
					{
						searchresult.ImgUrl = "https://ascii2d.net" + element.GetAttribute("src");
					}
					IElement element2 = htmlCollection[1].QuerySelector("h6 small");
					if (element2 != null)
					{
						searchresult.Source = element2.TextContent;
					}
					return true;
				}
			}
			catch (Exception ex)
			{
				CQ.Log(ex.ToString());
				return false;
			}
			return false;
		}
	}
}
